package unei;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by sunlei on 2015/4/25.
 */
public class DeadLock {

    private static Lock lock1=new ReentrantLock();
    private static Lock lock2=new ReentrantLock();

    public static void main(String[] args){
        System.out.println(Thread.currentThread().getId());
        Thread th1=new Thread(new MyThread());
        Thread th2=new Thread(new MyThread2());

        th1.start();
        th2.start();
    }

    public static class MyThread implements Runnable{
        @Override
        public void run() {
            try{
                lock1.lock();
                Thread.sleep(2000);
                lock2.lock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally{
                lock2.lock();
                lock1.unlock();
            }
        }
    }

    public static class MyThread2 implements Runnable{
        @Override
        public void run() {
            try{
                lock2.lock();
                Thread.sleep(2000);
                lock1.lock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally{
                lock1.unlock();
                lock2.unlock();
            }
        }
    }
}
